/**
 * 
 */
package systole.view.crud.patient.patientComponents.controller;

import java.util.Iterator;
import java.util.List;

import javax.swing.JOptionPane;

import org.jdesktop.swingx.JXTable;
import systole.domain.persons.Patient;

import systole.view.crud.patient.TableMouseAdapterPatientComponent;
import systole.view.crud.tableModels.SystoleTableModel;

/**
 * @author jmj
 * 
 */
public abstract class ControllerViewPatientComponent {

    protected SystoleTableModel tableModel;
    protected JXTable table;
    protected List entityList;
    protected Patient patient;
    private boolean editing;
    protected ControllerEditionPatienComponent controllerEntityEdition;

    /**
     * @param table
     * @param patient
     *
     */
    public ControllerViewPatientComponent(JXTable table, Patient patient, boolean editing) {
        super();
        this.table = table;
        table.addMouseListener(new TableMouseAdapterPatientComponent(this));
        this.patient = patient;
        this.editing = editing;
    }

    /**
     * Method to reload the entity list
     */
    protected abstract void refreshList();

    /**
     * Method to remove an entity from list
     */
    protected abstract void deleteEntity(Object entity);

    /**
     * edit the entity selected
     */
    public void editEntity() {
        int selected = this.table.getSelectedRow();
        if (selected != -1) {
            this.controllerEntityEdition.editEntity(this.entityList.get(selected));
            this.refreshList();
        }
    }

    /**
     * create a new entity
     */
    public void newEntity() {
        this.controllerEntityEdition.newEntity();
        this.refreshList();

    }

    /**
     * delete the entity selected
     */
    public void removeEntity() {
        int selected = this.table.getSelectedRow();
        if (selected != -1) {
            if (this.getUserConfirmation("¿Esta seguro que desea eliminar el item seleccionado?",
                    "Eliminar")) {
                this.deleteEntity(this.entityList.get(selected));
                this.refreshList();
            }
        }
    }

  

    /**
     *
     * @return if user confirm operation
     */
    protected boolean getUserConfirmation(String msg, String title) {
        return JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(null,
                msg, title, JOptionPane.OK_CANCEL_OPTION);
    }

    public void clearList() {
        if (!this.entityList.isEmpty()) {
            if (this.getUserConfirmation("¿Esta seguro que desea eliminar todos los items?",
                    "Vaciar Lista")) {
                Iterator it = this.entityList.iterator();
                while (it.hasNext()) {
                    this.deleteEntity(it.next());
                }
                this.refreshList();
            }
        }
    }

    /**
     * @return the editing
     */
    protected boolean isEditing() {
        return editing;
    }
}
